import axios, { type InternalAxiosRequestConfig } from 'axios';
import { useTokenStore } from '@/stores/myToken';
import { ElMessage } from 'element-plus'
import router from '@/router'

const store = useTokenStore();

const request = axios.create({
  // baseURL: import.meta.env.VITE_API_URL,
  // timeout: 5000
});

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  config.headers = config.headers || {}; // 无需手动指定类型，axios 1.9.0 会自动推断
  //如果store存在token则将token设置到头部中
  if (store.token) {
    config.headers.Authorization = store.token;
  }
  return config;
});



request.interceptors.response.use(
  res => {
    return res;
  },
  err => {
    if (err.response.status === 401) {
      // 如果token无效，重定向到登录页面
      router.push('/login');
      store.removeToken()
    }
    return Promise.reject(err);
  }
);




export default request;
